package com.itheima.demo5owns;

import javax.swing.*;
import javax.swing.Timer;
import javax.swing.border.LineBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.*;
import java.util.List;

public class RoomGUI extends JFrame {

    private Map<String, List<Card>> players;
    private List<Card> bottomCards;
    private Map<String, JPanel> playerCardsPanels = new HashMap<>();
    private List<String> playerOrder;
    private int currentPlayerIndex = 0;
    private int cardsDealt = 0;
    private static final int TOTAL_CARDS_PER_PLAYER = 17;
    private Timer timer;
    private JPanel mainPanel;
    private JPanel bottomPanel;
    private final Color BG_COLOR = new Color(0, 100, 0); // 深绿色背景

    public RoomGUI() {
        initializeUI();
        resetGame();
    }

    private void initializeUI() {
        setTitle("斗地主发牌系统");
        setSize(1000, 650);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        getContentPane().setBackground(BG_COLOR);

        mainPanel = new JPanel(new BorderLayout());
        mainPanel.setBackground(BG_COLOR);
        mainPanel.setOpaque(true);

        // 添加重新发牌按钮
        JButton resetButton = new JButton("洗牌并重新发牌");
        resetButton.setBackground(new Color(240, 240, 240));
        resetButton.setForeground(BG_COLOR);
        resetButton.setFocusPainted(false);
        resetButton.addActionListener(e -> resetGame());

        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        buttonPanel.setBackground(BG_COLOR);
        buttonPanel.add(resetButton);
        mainPanel.add(buttonPanel, BorderLayout.NORTH);

        add(mainPanel);
    }

    private void resetGame() {
        mainPanel.removeAll();
        initializeUI();

        Room room = new Room();
        List<Card> allCards = room.getCards();

        players = new HashMap<>();
        players.put("小李", new ArrayList<>(allCards.subList(0, 17)));
        players.put("小王", new ArrayList<>(allCards.subList(17, 34)));
        players.put("小花", new ArrayList<>(allCards.subList(34, 51)));
        bottomCards = new ArrayList<>(allCards.subList(51, 54));

        playerOrder = new ArrayList<>(players.keySet());
        currentPlayerIndex = 0;
        cardsDealt = 0;

        JPanel playerPanel = new JPanel(new GridLayout(3, 1, 10, 10));
        playerPanel.setBackground(BG_COLOR);
        playerPanel.setOpaque(true);

        for (String playerName : players.keySet()) {
            JPanel panel = createPlayerPanel(playerName);
            playerPanel.add(panel);
        }

        bottomPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 10));
        bottomPanel.setBackground(BG_COLOR);
        bottomPanel.setOpaque(true);
        bottomPanel.setBorder(BorderFactory.createTitledBorder("底牌"));

        mainPanel.add(playerPanel, BorderLayout.CENTER);
        mainPanel.add(bottomPanel, BorderLayout.SOUTH);
        mainPanel.revalidate();
        mainPanel.repaint();

        startDealing();
    }

    private JPanel createPlayerPanel(String playerName) {
        JPanel panel = new JPanel();
        panel.setBackground(BG_COLOR);
        panel.setOpaque(true);
        panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));

        panel.setBorder(BorderFactory.createTitledBorder(
                BorderFactory.createLineBorder(Color.WHITE, 2),
                playerName,
                javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION,
                javax.swing.border.TitledBorder.DEFAULT_POSITION,
                new Font("楷体", Font.BOLD, 16),
                Color.WHITE
        ));

        JPanel cardsPanel = new JPanel();
        cardsPanel.setBackground(BG_COLOR);
        cardsPanel.setOpaque(true);
        cardsPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));
        playerCardsPanels.put(playerName, cardsPanel);

        JScrollPane scrollPane = new JScrollPane(cardsPanel);
        scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        scrollPane.setBackground(BG_COLOR);
        scrollPane.setOpaque(true);
        scrollPane.getViewport().setOpaque(true);
        panel.add(scrollPane);

        return panel;
    }

    private void startDealing() {
        timer = new Timer(100, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (cardsDealt < TOTAL_CARDS_PER_PLAYER * playerOrder.size()) {
                    String currentPlayer = playerOrder.get(currentPlayerIndex);
                    List<Card> cards = players.get(currentPlayer);
                    JPanel cardsPanel = playerCardsPanels.get(currentPlayer);

                    int cardIndex = cardsDealt % TOTAL_CARDS_PER_PLAYER;
                    if (cardIndex < cards.size()) {
                        Card card = cards.get(cardIndex);
                        JLabel cardLabel = createStyledCardLabel(card);
                        cardsPanel.add(cardLabel, 0);
                        cardsPanel.revalidate();
                        cardsPanel.repaint();
                    }

                    currentPlayerIndex = (currentPlayerIndex + 1) % playerOrder.size();
                    cardsDealt++;

                } else {
                    ((Timer) e.getSource()).stop();
                    showSortingMessage();
                }
            }
        });
        timer.start();
    }

    private JLabel createStyledCardLabel(Card card) {
        JLabel label = new JLabel(card.toString()) {
            @Override
            protected void paintComponent(Graphics g) {
                Graphics2D g2d = (Graphics2D) g.create();
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

                // 渐变背景
                GradientPaint gp = new GradientPaint(
                        0, 0, new Color(240, 240, 240),
                        getWidth(), getHeight(), new Color(200, 200, 200));
                g2d.setPaint(gp);
                g2d.fillRoundRect(2, 2, getWidth()-4, getHeight()-4, 12, 12);

                // 边框
                g2d.setColor(new Color(0, 100, 0));
                g2d.setStroke(new BasicStroke(2));
                g2d.drawRoundRect(2, 2, getWidth()-4, getHeight()-4, 12, 12);

                g2d.dispose();
                super.paintComponent(g);
            }
        };

        label.setFont(new Font("Arial", Font.BOLD, 14));
        label.setForeground(Color.BLACK);
        label.setPreferredSize(new Dimension(50, 70));
        label.setHorizontalAlignment(SwingConstants.CENTER);
        label.setVerticalAlignment(SwingConstants.CENTER);
        label.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        return label;
    }

    private void showSortingMessage() {
        JOptionPane pane = new JOptionPane("正在排序...", JOptionPane.INFORMATION_MESSAGE);
        JDialog dialog = pane.createDialog("系统提示");
        dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
        dialog.setVisible(true);

        // 执行排序
        sortAllPlayersCards();
        dialog.dispose();

        // 显示底牌
        showBottomCards();
    }

    private void sortAllPlayersCards() {
        for (Map.Entry<String, List<Card>> entry : players.entrySet()) {
            List<Card> cards = entry.getValue();
            Collections.sort(cards, new Comparator<Card>() {
                @Override
                public int compare(Card o1, Card o2) {
                    // o1  2♠
                    // o2  J♠
                    return o1.getNum() - o2.getNum();
                }
            });
            JPanel panel = playerCardsPanels.get(entry.getKey());
            panel.removeAll();

            for (Card card : cards) {
                JLabel label = createStyledCardLabel(card);
                panel.add(label);
            }
            panel.revalidate();
            panel.repaint();
        }
    }

    private void showBottomCards() {
        bottomPanel.removeAll();
        for (Card card : bottomCards) {
            JLabel cardLabel = createStyledCardLabel(card);
            bottomPanel.add(cardLabel);
        }
        bottomPanel.revalidate();
        bottomPanel.repaint();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            RoomGUI gui = new RoomGUI();
            gui.setVisible(true);
        });
    }
}